import axios from 'axios'
import JSONBig from 'json-bigint'
import store from '@/store'
import router from '@/router'
const request = axios.create({
  baseURL: 'http://toutiao.itheima.net',

  transformResponse: [function (data) {
    try {
      // 如果转换成功则返回转换的数据结果
      return JSONBig.parse(data)
    } catch (err) {
      // 如果转换失败，则包装为统一数据格式并返回
      return {
        data
      }
    }
  }]
})
request.interceptors.request.use(
  function (config) {
    const user = store.state.user
    if (user) {
      config.headers.Authorization = `Bearer ${user.token}`
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)
request.interceptors.response.use(
  function (response) {
    return response
  },
  async function (error) {
    console.dir(error)
    if (error.response && error.response.status === 401) {
      const user = store.state.user
      if (!user || !user.refresh_token) {
        router.push('/login')
        return
      }
      try {
        const res = await axios({
          method: 'PUT',
          url: 'http://ttapi.research.itcast.cn//v1_0/authorizations',
          headers: {
            Authorization: `Bearer ${user.refresh_token}`
          }
        })
        console.log('刷新 token  成功', res)
        store.commit('setUser', {
          token: res.data.data.token,
          refresh_token: user.refresh_token
        })
        return request(error.config)
      } catch (err) {
        console.log('请求刷线 token 失败', err)
        router.push('/login')
      }
    }
    return Promise.reject(error)
  }
)
export default request
